document.addEventListener('DOMContentLoaded', () => {
    // 导航功能
    const navItems = document.querySelectorAll('.nav-item');
    const featureSections = document.querySelectorAll('.feature-section');
    const token = localStorage.getItem('token');
    if (!token && window.location.pathname !== '/login.html') {
        window.location.href = 'login.html';
        return;
    }
    // 默认显示第一个功能区块
    if(featureSections.length > 0) {
        featureSections[0].classList.add('active');
        if(navItems.length > 0) {
            navItems[0].classList.add('active');
        }
    }
    
    // 显示指定功能区块
    function showFeatureSection(sectionId) {
        // 隐藏所有功能区块
        featureSections.forEach(section => section.classList.remove('active'));
        
        // 移除导航栏高亮
        navItems.forEach(nav => nav.classList.remove('active'));
        
        // 显示目标区块
        const targetSection = document.getElementById(sectionId);
        if (targetSection) {
            targetSection.classList.add('active');
            
            // 如果是主导航菜单项，高亮对应按钮
            const matchingNavItem = document.querySelector(`.nav-item[data-tab="${sectionId}"]`);
            if (matchingNavItem) {
                matchingNavItem.classList.add('active');
            }
        }
    }
    
    // 为每个导航项添加点击事件
    navItems.forEach(item => {
        item.addEventListener('click', () => {
            const tabId = item.dataset.tab;
            showFeatureSection(tabId);
        });
    });
    
    // 侧栏功能
    const userMenuBtn = document.getElementById('userMenuBtn');
    const closeSidebarBtn = document.getElementById('closeSidebar');
    const userSidebar = document.getElementById('userSidebar');
    const sidebarOverlay = document.getElementById('sidebarOverlay');
    
    // 打开侧栏
    userMenuBtn.addEventListener('click', () => {
        userSidebar.classList.add('active');
        sidebarOverlay.classList.add('active');
        document.body.style.overflow = 'hidden'; // 防止页面滚动
    });
    
    // 关闭侧栏
    function closeSidebar() {
        userSidebar.classList.remove('active');
        sidebarOverlay.classList.remove('active');
        document.body.style.overflow = ''; // 恢复页面滚动
    }
    
    closeSidebarBtn.addEventListener('click', closeSidebar);
    sidebarOverlay.addEventListener('click', closeSidebar);
    
    // 侧栏菜单功能
    const sidebarItems = document.querySelectorAll('.sidebar-item');
    sidebarItems.forEach(item => {
        item.addEventListener('click', async (e) => {
            e.preventDefault();
            const action = item.dataset.action;

            switch (action) {
                case 'profile':
                    showFeatureSection('profile');
                    closeSidebar();
                    break;
                case 'history':
                    showFeatureSection('history');
                    // 加载历史记录
                    if (typeof loadHistory === 'function') {
                        loadHistory();
                    }
                    closeSidebar();
                    break;
                case 'settings':
                    showFeatureSection('profile'); // 使用个人资料页面作为设置
                    closeSidebar();
                    break;
                case 'help':
                    showFeatureSection('help');
                    closeSidebar();
                    break;
                case 'logout':
                    if (confirm('确定要退出登录吗？')) {
                        try {
                            const token = localStorage.getItem('token');
                            const response = await fetch('http://localhost:5000/api/auth/logout', {
                                method: 'POST',
                                headers: {
                                    'Authorization': `Bearer ${token}`,
                                    'Content-Type': 'application/json'
                                },
                                credentials: 'include'
                            });

                            const data = await response.json();
                            if (data.success) {
                                // 重置登录状态
                                resetLoginState();
                                // 返回第一个功能区块
                                showFeatureSection(featureSections[0].id);
                            } else {
                                alert('退出登录失败：' + (data.message || '未知错误'));
                            }
                        } catch (error) {
                            console.error('退出登录失败:', error);
                            alert('退出登录失败，请重试');
                        } finally {
                            closeSidebar();
                        }
                    }
                    break;
            }
        });
    });
    checkLoginStatus(); 
    // 检查用户登录状态
    async function checkLoginStatus() {
    const token = localStorage.getItem('token');
    if (token) {
        try {
            const response = await fetch('http://localhost:5000/api/auth/verify', {
                method: 'GET',
                headers: {
                    'Authorization': `Bearer ${token}`,
                    'Accept': 'application/json'
                },
                mode: 'cors'
            });

            const data = await response.json();  // 获取响应数据

            if (response.ok) {
                if (data.success) {
                    // 更新用户信息显示
                    document.getElementById('userInfo').textContent = data.username;
                    document.getElementById('sidebarUsername').textContent = data.username;

                    // 正确切换登录状态的显示
                    const userLoggedIn = document.getElementById('userLoggedIn');
                    const userNotLoggedIn = document.getElementById('userNotLoggedIn');

                    if (userLoggedIn && userNotLoggedIn) {
                        userLoggedIn.classList.remove('hidden');  // 显示已登录状态
                        userNotLoggedIn.classList.add('hidden');  // 隐藏未登录状态
                    }
                } else {
                    console.error('验证失败:', data.message);
                    resetLoginState();
                }
            } else {
                if (response.status === 401 || response.status === 422) {
                    console.log('Token 无效或过期');
                    resetLoginState();
                    window.location.href = 'login.html';
                }
            }
        } catch (error) {
            console.error('验证登录状态失败:', error);
            resetLoginState();
        }
    } else {
        resetLoginState();
        window.location.href = 'login.html';
    }
}

    function resetLoginState()
    {
        localStorage.removeItem('token');

        const userInfo = document.getElementById('userInfo');
        const sidebarUsername = document.getElementById('sidebarUsername');
        const userLoggedIn = document.getElementById('userLoggedIn');
        const userNotLoggedIn = document.getElementById('userNotLoggedIn');

        // 安全地更新 DOM
        if (userInfo) userInfo.textContent = '未登录';
        if (sidebarUsername) sidebarUsername.textContent = '未登录';

        // 正确切换显示状态
        if (userLoggedIn) userLoggedIn.classList.add('hidden');
        if (userNotLoggedIn) userNotLoggedIn.classList.remove('hidden');
    }
})